package net.xo68.destiny.manager.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.manager.entity.DistributedLock;
import net.xo68.destiny.manager.mapper.DistributedLockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;



/** 
 * DistributedLock Service
 * @author wuxie(16349023@qq.com)
 * @date 2020年12月17日 14:16:49
 *
 */
@Slf4j
@Service
public class DistributedLockService{
    
    @Autowired
    private DistributedLockMapper distributedLockMapper;

    public DistributedLock find(String lockKey) {
        return  distributedLockMapper.find(lockKey);
    }

    public DistributedLock insert(DistributedLock distributedLock) {
        distributedLockMapper.insert(distributedLock);
        return distributedLock;
    }

    public DistributedLock update(DistributedLock distributedLock) {
        distributedLockMapper.update(distributedLock);
        return distributedLock;
    }

    public int updateStatus(String lockKey,String lockStatus){
        return distributedLockMapper.updateStatus(lockKey,lockStatus);
    }


    public int delete(String lockKey) {
        return distributedLockMapper.delete(lockKey);
    }
    
    public List<DistributedLock> list() {
        return distributedLockMapper.list();
    }
	
	public PageInfo<DistributedLock> list(int pageNumber,int pageSize) {
        PageHelper.startPage(pageNumber, pageSize,true);
        List<DistributedLock> docs = distributedLockMapper.list();
        PageInfo<DistributedLock> pageInfo = new PageInfo<DistributedLock>(docs);
        return pageInfo;
    }

    /**
     * 非周期锁信息 上锁处理
     * @param lock
     */
    @Transactional
    public void insertLockInfo(DistributedLock lock){
        distributedLockMapper.deleteExpired(lock.getLockKey(),lock.getCreateTime());
        distributedLockMapper.insert(lock);
    }

    /**
     * 周期锁信息 上锁处理
     * @param lock
     */
    @Transactional
    public void insertPeriodLockInfo(DistributedLock lock){
        distributedLockMapper.deleteExpired(lock.getLockKey(),lock.getCreateTime());
        distributedLockMapper.deleteExpiredPeriod(lock.getLockKey(),lock.getCreateTime());
        distributedLockMapper.insert(lock);
    }
}